﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using FootballCourt.Data.Abstract;
using System.Collections.Generic;
using log4net;
using System.Data;

namespace FootballCourt.Data.Concrete
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        protected readonly DbContext fbContext;
        protected readonly DbSet<T> dbSet;
        private static ILog _logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 

        public BaseRepository(IFootballCourtContext context)
        {
            this.fbContext = context.CurrentContext;
            this.dbSet = this.fbContext.Set<T>();
        }

        #region IBaseRepository
        public T Get(object id)
        {
            try
            {
                return this.dbSet.Find(id);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            return null;
        }
        public T Get(Expression<Func<T, bool>> predicate)
        {
            try
            {
                return this.dbSet.FirstOrDefault(predicate);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            return null;
        }
        public IEnumerable<T> GetAll()
        {
            try
            {
                return this.dbSet.ToList();
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            return null;
        }
        public IEnumerable<T> GetAll(Expression<Func<T, bool>> predicate)
        {
            try
            {
                return this.dbSet.Where(predicate);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            return null;
        }
        public void Update(T entity)
        {
            this.fbContext.Entry(entity).State = EntityState.Modified;
        }
        public void Delete(T entity)
        {
            this.fbContext.Entry(entity).State = EntityState.Deleted;
        }
        public void Insert(T entity)
        {
            this.fbContext.Entry(entity).State = EntityState.Added;
        }
        #endregion
    }
}
